/**
 * 处理书本接口的业务逻辑
 */
const { createBook, delBook, updateBook, getBookInfo } = require('../service/book')

class BookController {
  // 新增书本
  async create(ctx, next) {
    // 获取数据
    const { title, author, publication_date, genre } = ctx.request.body

    try {
      // 创建书本
      const res = await createBook(title, author, publication_date, genre, '在库')
      ctx.body = {
        code: 200,
        msg: '新增书本成功',
        data: res
      }
    }
    catch (error) {
      console.error(error);
      ctx.body = {
        code: 500,
        msg: '新增书本失败',
        error: error.message
      };
    }
  }

  // 删除书本
  async del(ctx, next) {
    const { book_id } = ctx.request.body;
    try {
      const res = await delBook(book_id);
      if (res === 0) {
        ctx.body = {
          code: 404,
          msg: '删除失败，找不到该书本'
        };
      } else {
        ctx.body = {
          code: 200,
          msg: '删除书本成功'
        };
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '删除书本失败',
        error: error.message
      };
    }
  }

  // 更新书本信息
  async update(ctx, next) {
    const { book_id, title, author, publication_date, genre } = ctx.request.body;

    try {
      const res = await updateBook(book_id, title, author, publication_date, genre)
      // update更新成功返回[1]
      if (res[0] === 1) {
        ctx.body = {
          code: 200,
          msg: '修改书本信息成功'
        };
      }
      else {
        ctx.body = {
          code: 404,
          msg: '未找到要修改的书本信息'
        };
      }
    } catch (error) {
      console.error(error);
      ctx.body = {
        code: 500,
        msg: '修改书本信息失败',
        error: error.message
      };
    }
  }

  // 获取书本列表（不传值就是获取全部）
  async list(ctx, next) {
    // 获取数据
    const { title, author, publication_date, genre, status } = ctx.request.body

    try {
      const res = await getBookInfo({ title, author, publication_date, genre, status })
      ctx.body = {
        code: 200,
        msg: '获取书本列表成功',
        data: res
      }
    }
    catch (error) {
      console.error(error);
      ctx.body = {
        code: 500,
        msg: '获取书本列表失败',
        error: error.message
      };
    }
  }

}

module.exports = new BookController()
